﻿using Common.Contract;
using Common.Contract.Authentication.Record;
using Common.Contract.ProductHandbook.Request;
using Common.Service.Command;
using CrossSelling.Model.Interface;
using CrossSelling.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrossSelling.Core.ServiceCommand.Admin
{
    public class UpdateQuestionServiceCommand : ProviderServiceCommand<IProviderFactory, UpdateChecklistQuestionRequest, ResponseRecord>
    {
        private UserRecord Dao;
        public UpdateQuestionServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(UpdateChecklistQuestionRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.Record == null)
            {
                throw new ArgumentException("Record must be set", "request");
            }
            if (request.DaoChange == null)
            {
                throw new ArgumentException("MSBO Dao must be set", "request");
            }
            else
            {
                Dao = Request.DaoChange;
            }
        }

        protected override bool OnExecute(ResponseRecord response)
        {
            try
            {
                bool isUpdate = true;
                if (Request.Record.QuestionId != 0)
                {
                    ChecklistQuestion question = new ChecklistQuestion
                    {
                        Title = Request.Record.Title,
                        QuestionId = Request.Record.QuestionId,
                        TitleEn = Request.Record.TitleEn,
                        ProductId = Request.Record.ProductId,
                        Status = 1
                    };
                    isUpdate = Providers.ProductHandbooks.UpdateQuestionChecklist(question);
                }
                else
                {
                    ChecklistQuestion question = new ChecklistQuestion
                    {
                        Title = Request.Record.Title,
                        QuestionId = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds,
                        TitleEn = Request.Record.TitleEn,
                        ProductId = Request.Record.ProductId,
                        Status = 1
                    };
                    isUpdate = Providers.ProductHandbooks.SaveQuestionChecklist(question);
                }

                return isUpdate;
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }
        }
    }
}
